package com.azure.bigstore.service;

import com.azure.bigstore.entity.Category;
import com.azure.bigstore.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by liuhuaibin on 2018/1/28.
 */
@Service
public class CategoryService {
    @Autowired
    private CategoryRepository categoryRepository;

    /**
     * 获取单个category
     * @param id category_id
     * @return category
     */
    public Category getCategory(String id){
        return categoryRepository.findOne(Long.valueOf(id));
    }

    /**
     *  add or update category
     * @param category  category_entity
     * @return category_entity
     */
    public Category saveCategory(Category category){
        Category parent = categoryRepository.findOne(category.getPid());
        if(parent != null){
            parent.setLeaf(false);
            categoryRepository.save(parent);
        }
        return categoryRepository.save(category);
    }

    /**
     * get all category_id
     * @return List<Long>
     */
    public List<Long> getCategoryIDs(){
        List<Category> categoriesGrade2 = categoryRepository.getCategoriesGrade2();
        List<Long> ids = null;
        for(Category ca: categoriesGrade2){
            ids.add(ca.getID());
        }
        return ids;
    }

    /**
     * 查询所有信息、层次输出
     * @return 树形结构集合
     */
    public List<Category> findAll2Tree() {
        List<Category> categories = new ArrayList<>();
        categories = findList(categories,0L);
        return categories;
    }
    /**
     * 根据传入的pid递归层次查询所有信息
     * @param list 放置节点的集合，递归后树形结构排列
     * @param pid 父节点id
     * @return 部分树形结构集合
     */
    public List<Category> findList(List<Category> list,long pid) {

        List<Category> result = categoryRepository.findByPid(pid);
        for(Category ca: result){
            list.add(ca);
            if(ca.isLeaf() == false){
                findList(list,ca.getID());
            }
        }
        return list;
    }

    /**
     * 删除节点，更新父节点
     * @param id 节点id
     * @param pid 父节点id
     */
    public void delete(long id, long pid) {
        //删除自己的子节点
        delete(id);
        //查看是否还有子节点，如果没有子节点则更新父节点
        List<Category> result = categoryRepository.findByPid(pid);
        if(result.size()>0){
            return;
        }
        //更新父节点
        Category patent = categoryRepository.findOne(pid);
        if(patent != null){
            patent.setLeaf(true);
            categoryRepository.save(patent);
        }

    }

    /**
     * 删除子节点
     * @param id 节点id
     */
    private void delete(long id) {
        List<Category> result = categoryRepository.findByPid(id);
        for(Category ca :result){
            delete(ca.getID());
        }

        categoryRepository.delete(id);
    }
}
